import json
import ColorAndStyle
from drawTwoDim import DrawTwoDim


class DrawLRPResult:
    def __init__(self):
        self._depots = []
        self._nodes = []
        self._depot_count = 0
        self._customer_count = 0
        self._s = None

    def draw(self, problem_file, result_file):
        self.read_instance(problem_file)
        self._s = DrawTwoDim(self._nodes)
        self.draw_nodes()
        self.read_lines(result_file)
        self._s.show('result-'+problem_file.split('.')[0])

    def read_instance(self, filename):
        with open(filename, 'r') as f:
            data = json.load(f)
            self._depot_count = len(data['depots'])
            self._customer_count = len(data['customers'])

            self._nodes = [[0, 0] for _ in range(self._depot_count + self._customer_count)]
            demands = [0 for _ in range(self._depot_count + self._customer_count)]
            for customer in data['customers']:
                index, x, y, demand = customer['index'], customer['x'], customer['y'], customer['demand']
                self._nodes[index][0] = x
                self._nodes[index][1] = y
                demands[index] = demand
            for depot in data['depots']:
                index, x, y, demand = depot['index'], depot['x'], depot['y'], depot['capacity']
                self._nodes[index][0] = x
                self._nodes[index][1] = y
                demands[index] = demand

    def draw_nodes(self):
        self._s.draw_nodes([x for x in range(self._depot_count)], [str(i) for i in range(self._depot_count)],
                           marksize=25)
        self._s.draw_nodes([x for x in range(self._depot_count, self._depot_count + self._customer_count)],
                           [str(i) for i in range(self._depot_count, self._depot_count + self._customer_count)],
                           color=ColorAndStyle.COLOR.YELLOW, marker=ColorAndStyle.STYLE.star)

    def read_lines(self, filename):
        with open(filename, 'r') as f:
            data = json.load(f)
            color_index = 0
            for index, depot in data.items():
                for route_index, route in depot.items():
                    if route_index == 'total demands' or route_index == 'vehicle number':
                        continue
                    arcs = []
                    for i in range(len(route) - 1):
                        arcs.append([route[i], route[i + 1]])
                    arcs.append([route[-1], route[0]])
                    self._s.draw_lines(arcs, color=ColorAndStyle.COLOR.COLORS[color_index])
                color_index += 1
                if color_index == len(ColorAndStyle.COLOR.COLORS):
                    color_index = 0


if __name__ == "__main__":
    s = DrawLRPResult()
    s.draw("100-5-1c.json", 'results.json')
